<template>
  <view class="profile-page">
    <!-- 自定义导航栏 -->
    <custom-navbar
      :title="'个人中心'"
      :background-color="'#FFFFFF'"
    ></custom-navbar>

    <!-- 用户信息卡片 -->
    <view class="user-card">
      <view class="user-info">
        <view class="avatar" @click="changeAvatar">
          <placeholder-image
            v-if="!userInfo.avatar"
            shape="circle"
            :text="
              userInfo.userName ? userInfo.userName.substring(0, 1) : '用户'
            "
            :width="160"
            :height="160"
          ></placeholder-image>
          <image
            v-else
            class="avatar-image"
            :src="userInfo.avatar"
            mode="aspectFill"
          ></image>
        </view>
        <view class="user-details">
          <view class="user-name">{{ userInfo.userName ?? '未登录' }}</view>
          <view class="login-btn" v-if="!userInfo.token" @click="login">点击登录</view>
        </view>
      </view>
    </view>

    <!-- 功能入口区 -->
    <view class="feature-section">
      <!-- 我的预约 -->
      <view
        class="feature-card"
        @click="navigateTo('/pages/profile/allvenues')"
		v-if="!isAdmin"
      >
        <view class="feature-header">
          <view class="feature-title">我的预约</view>
          <view class="feature-more">
            <text class="more-text">查看全部</text>
            <uni-icons type="right" size="14" color="#999"></uni-icons>
          </view>
        </view>
        <view v-if="myBookings.length > 0 && userInfo.token" class="booking-list">
          <view
            class="booking-item"
            v-for="(item, index) in myBookings"
            :key="index"
          >
            <view class="booking-left">
              <view class="booking-title">人体生命科学馆参观预约</view>
              <view class="booking-info">{{ formatDate(item.bookTime) }}</view>
            </view>
            <view class="booking-status" :class="item.status">{{
              getStatusText(item.status)
            }}</view>
          </view>
        </view>
        <view v-else class="empty-tip">
          <text class="empty-text">暂无预约记录</text>
        </view>
      </view>
	  
	  <!-- 预约审批 -->
	  <view
	    class="feature-card"
	    @click="navigateTo('/pages/profile/allvenues')"
		v-if="isAdmin"
	  >
	    <view class="feature-header">
	      <view class="feature-title">预约审批</view>
	      <view class="feature-more">
	        <text class="more-text">查看全部</text>
	        <uni-icons type="right" size="14" color="#999"></uni-icons>
	      </view>
	    </view>
	    <view v-if="approveList.length > 0 && userInfo.token" class="booking-list">
	      <view
	        class="booking-item"
	        v-for="(item, index) in approveList"
	        :key="index"
	      >
	        <view class="booking-left">
	          <view class="booking-title">人体生命科学馆参观预约</view>
	          <view class="booking-info">预约时间: {{ formatDate(item.bookTime) }}</view>
	          <view class="booking-info">发起账号: {{ item.account }}</view>
	          <view class="booking-info">领队姓名: {{ item.realname }}</view>
			  <view class="booking-info">联系电话: {{ item.phone }}</view>
	        </view>
	        <view class="booking-status" :class="item.status">{{
	          getStatusText(item.status)
	        }}</view>
	      </view>
	    </view>
	    <view v-else class="empty-tip">
	      <text class="empty-text">暂无预约记录</text>
	    </view>
	  </view>

      <!-- 功能入口菜单 -->
      <view class="menu-card">
        <view class="menu-section">
          <view
            class="menu-item"
            v-for="(item, index) in menuItems1"
            :key="index"
            @click="navigateTo(item.url)"
          >
            <view class="menu-icon">
              <uni-icons
                :type="item.icon"
                size="22"
                color="#5a8dee"
              ></uni-icons>
            </view>
            <view class="menu-name">{{ item.name }}</view>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>

        <view class="menu-divider"></view>

        <view class="menu-section">
          <view
            class="menu-item"
            v-for="(item, index) in menuItems2"
            :key="index"
            @click="navigateTo(item.url)"
          >
            <view class="menu-icon">
              <uni-icons
                :type="item.icon"
                size="22"
                color="#5a8dee"
              ></uni-icons>
            </view>
            <view class="menu-name">{{ item.name }}</view>
            <uni-icons type="right" size="16" color="#999"></uni-icons>
          </view>
        </view>
      </view>

      <!-- 退出登录按钮 -->
      <view class="logout-btn" v-if="userInfo.token" @click="logout"
        >退出登录</view
      >
    </view>

    <!-- 底部标签栏 -->
    <tab-bar :current="3"></tab-bar>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from "vue";
import CustomNavbar from "@/components/custom-navbar/index.vue";
import TabBar from "@/components/tab-bar/index.vue";
import PlaceholderImage from "@/components/placeholder-image/index.vue";
import { request } from "@/utils/request";

// 退出登录请求接口
const reqLogout = (params) => {
	return request({
	  url: "/user/logout",
	  method: "post",
	  params: params
	})
}

// 获取参观记录请求接口
const reqGetVenues = (data) => {
	return request({
	  url: "/venues/logs",
	  method: "post",
	  data: JSON.stringify(data)
	})
}

// 获取预约审批列表
const reqGetApproveList = () => {
	return request({
		url: "/mine/perList",
		method: "GET"
	})
}

// 用户信息
const userInfo = ref(uni.getStorageSync('userInfo'));
const isAdmin = ref(uni.getStorageSync('isAdmin'))
// 我的预约列表
const myBookings = ref([]);
// 预约审批列表
const approveList = ref([]);

// 格式化为 "YYYY-MM-DD HH:mm:ss"
const formatDate = (dateStr) => {
	const date = new Date(dateStr);
	
	const formattedDate = new Intl.DateTimeFormat("zh-CN", {
	  year: "numeric",
	  month: "2-digit",
	  day: "2-digit",
	  hour: "2-digit",
	  minute: "2-digit",
	  second: "2-digit",
	  hour12: false, // 24小时制
	}).format(date);
	
	return formattedDate
}


// 功能菜单项
const menuItems1 = ref([
  {
    name: "我的收藏",
    icon: "star",
    url: "/pages/profile/my-favorites",
  },
  {
    name: "浏览历史",
    icon: "calendar",
    url: "/pages/profile/browse-history",
  },
]);

const menuItems2 = ref([
  {
    name: "设置",
    icon: "gear",
    url: "/pages/profile/settings",
  },
  {
    name: "关于我们",
    icon: "info",
    url: "/pages/profile/about",
  },
  {
    name: "意见反馈",
    icon: "chat",
    url: "/pages/profile/feedback",
  },
]);

// 获取预约状态文本
const getStatusText = (status) => {
  switch (status) {
    case "WAIT":
      return isAdmin.value ? "待审批" : "待参观";
    case "AGREE":
      return "已同意";
    case "REJECT":
      return "已拒绝";
    default:
      return "未知状态";
  }
};

// 页面跳转
const navigateTo = (url) => {
  uni.navigateTo({
    url,
  });
};

// 更换头像
const changeAvatar = () => {
  if (!userInfo) {
	  uni.showToast({
	    title: "请先登录",
	    icon: "warning",
	  });
	  return
  }
  
  uni.showActionSheet({
    itemList: ["从相册选择", "拍照"],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 从相册选择
        uni.chooseImage({
          count: 1,
          sizeType: ["compressed"],
          sourceType: ["album"],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            userInfo.value.avatar = tempFilePath;
          },
        });
      } else if (res.tapIndex === 1) {
        // 拍照
        uni.chooseImage({
          count: 1,
          sizeType: ["compressed"],
          sourceType: ["camera"],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0];
            userInfo.value.avatar = tempFilePath;
          },
        });
      }
    },
  });
};

// 登录
const login = () => {
  uni.navigateTo({
    url: "/pages/login/index",
  });
};

// 退出登录
const logout = async () => {
  uni.showModal({
    title: "提示",
    content: "确定要退出登录吗？",
    success: async (res) => {
	  const response = await reqLogout({userId: userInfo.value.userId, token: userInfo.value.token})
		
	  if (response.code != 200) {
		// 退出登录失败
		uni.showToast({
		  title: "退出登录失败",
		  icon: "error",
		});
			
		return
	  }
	  
	  uni.removeStorageSync('token')
	  uni.removeStorageSync('userInfo')
	  uni.removeStorageSync('isAdmin')
	  userInfo.value = {}

	  uni.showToast({
        title: "已退出登录",
        icon: "success",
      });
    },
  });
};

watch(() => userInfo.value.token, async (newVal) => {
	if (newVal) {
		if (userInfo.value && !isAdmin.value) {
			const list = await reqGetVenues({userId: userInfo.value.userId})
			myBookings.value = list.slice(0, 3)
		}
		if (isAdmin.value) {
			const res = await reqGetApproveList()
			approveList.value = res  
		}
	}
})

onMounted(async() => {
  // 监听登录状态变化
  uni.$on('loginStatusChanged', (data) => {
    userInfo.value = data.userInfo
	isAdmin.value = uni.getStorageSync('isAdmin')
  });
  uni.$on('UpdateBooking', async (data) => {
	if (userInfo.value && !isAdmin.value) {
		const list = await reqGetVenues({userId: userInfo.value.userId})
		myBookings.value = list.slice(0, 3)
	}
	if (isAdmin.value) {
		const res = await reqGetApproveList()
		approveList.value = res  
	}
  })
  uni.$on('approve', async (data) => {
	if (userInfo.value && !isAdmin.value) {
		const list = await reqGetVenues({userId: userInfo.value.userId})
		myBookings.value = list.slice(0, 3)
	}
	if (isAdmin.value) {
		const res = await reqGetApproveList()
		approveList.value = res  
	}
  })
  if (userInfo.value && !isAdmin.value) {
	const list = await reqGetVenues({userId: userInfo.value.userId})
	myBookings.value = list.slice(0, 3)
  }
  if (isAdmin.value) {
	const res = await reqGetApproveList()
	approveList.value = res  
  }
});

onUnmounted(() => {
  uni.$off('loginStatusChanged'); // 清除监听
  uni.$off('UpdateBooking');
  uni.$off('approve');
});
</script>

<style lang="scss" scoped>
.profile-page {
  background-color: $uni-bg-color-grey;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

// 用户卡片样式
.user-card {
  background: $gradient-primary;
  padding: $spacer-4 $spacer-4 $spacer-8;
  border-radius: 0 0 30rpx 30rpx;
  margin-bottom: $spacer-4;
}

.user-info {
  display: flex;
  align-items: center;
  margin-top: 60rpx; // 留出自定义导航栏的空间
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border-radius: 50%;
  overflow: hidden;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  background-color: rgba(255, 255, 255, 0.2);
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.user-details {
  margin-left: $spacer-4;
}

.user-name {
  font-size: $uni-font-size-lg;
  color: $uni-text-color-inverse;
  font-weight: 500;
  margin-bottom: $spacer-2;
}

.user-tag {
  display: inline-block;
  font-size: $uni-font-size-sm;
  color: $uni-text-color-inverse;
  background-color: rgba(255, 255, 255, 0.2);
  padding: $spacer-1 $spacer-2;
  border-radius: $uni-border-radius-sm;
}

.login-btn {
  display: inline-block;
  font-size: $uni-font-size-sm;
  color: $uni-color-primary;
  background-color: $uni-text-color-inverse;
  padding: $spacer-1 $spacer-3;
  border-radius: $uni-border-radius-sm;
}

// 功能区域样式
.feature-section {
  padding: 0 $spacer-4;
}

// 通用卡片样式
.feature-card,
.menu-card {
  background-color: $uni-bg-color;
  border-radius: $uni-border-radius-lg;
  margin-bottom: $spacer-4;
  padding: $spacer-4;
  box-shadow: $box-shadow-card;
}

// 我的预约卡片
.feature-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: $spacer-4;
}

.feature-title {
  font-size: $uni-font-size-lg;
  font-weight: 500;
}

.feature-more {
  display: flex;
  align-items: center;

  .more-text {
    font-size: $uni-font-size-sm;
    color: $uni-text-color-grey;
    margin-right: $spacer-1;
  }
}

.booking-list {
  display: flex;
  flex-direction: column;
}

.booking-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacer-3 0;
  border-bottom: 1px solid $uni-border-color;

  &:last-child {
    border-bottom: none;
  }
}

.booking-left {
  flex: 1;
}

.booking-title {
  font-size: $uni-font-size-base;
  margin-bottom: $spacer-1;
}

.booking-info {
  font-size: $uni-font-size-sm;
  color: $uni-text-color-grey;
}

.booking-status {
  font-size: $uni-font-size-sm;
  padding: $spacer-1 $spacer-2;
  border-radius: $uni-border-radius-sm;

  &.WAIT {
    color: $uni-color-warning;
    background-color: rgba($uni-color-warning, 0.1);
  }

  &.AGREE {
    color: $uni-color-success;
    background-color: rgba($uni-color-success, 0.1);
  }

  &.REJECT {
    color: $uni-color-error;
    background-color: rgba($uni-color-error, 0.1);
  }
}

.empty-tip {
  padding: $spacer-4 0;
  text-align: center;

  .empty-text {
    font-size: $uni-font-size-base;
    color: $uni-text-color-grey;
  }
}

// 菜单样式
.menu-section {
  display: flex;
  flex-direction: column;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: $spacer-3 0;

  &:not(:last-child) {
    border-bottom: 1px solid $uni-border-color;
  }
}

.menu-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80rpx;
}

.menu-name {
  flex: 1;
  font-size: $uni-font-size-base;
  margin-left: $spacer-2;
}

.menu-divider {
  height: 20rpx;
  margin: $spacer-2 (-$spacer-4);
  background-color: $uni-bg-color-grey;
}

// 退出登录按钮
.logout-btn {
  text-align: center;
  padding: $spacer-4 0;
  margin: $spacer-6 0;
  background-color: $uni-bg-color;
  color: $uni-color-error;
  font-size: $uni-font-size-base;
  border-radius: $uni-border-radius-lg;
  box-shadow: $box-shadow-card;
}
</style>
